const MongoClient = require('mongodb').MongoClient;

// 数据库连接地址
const url = 'mongodb://127.0.0.1:27017';
// 数据库名称
const dbName = 'hk';
// 表名
const collectionName = 'users';

module.exports = {
    dbConnect(callback) {
        MongoClient.connect(url, (err, client) => {
            if (err) {
                return console.log('连接数据库失败', err);
            }

            callback && callback(client);

        });
    },
    dbGetAll(client, callback) {
        client.db(dbName).collection(collectionName).find().toArray((err, data) => {
            if (err) {
                return console.log('读取数据失败', err);
            }
            console.log(data);

            let data_obj = {
                list: data
            }
            callback && callback(data_obj);
            client.close();
        });
    },
    dbGetById(client, id, callback) {
        client.db(dbName).collection(collectionName).find({ _id: id }).toArray((err, data) => {
            if (err) {
                return console.log('读取数据失败', err);
            }
            console.log(data);

            callback && callback(data)
                // res.render(path.join(__dirname, 'pages', 'details.html'), data[0]);
            client.close();
        });
    },
    dbAdd(client, data, callback) {
        client.db(dbName).collection(collectionName).insert(data);
        callback && callback();
        client.close();
    },
    dbDelete(client, id, callback) {
        client.db(dbName).collection(collectionName).deleteOne({ _id: id });
        callback && callback();
        client.close();

    }
}